<template>
  <div class="chat-window">
    <div class="chat-header">
      <h2>{{ courseName }} - 课程聊天室</h2>
    </div>
    <div class="chat-messages" ref="messageContainer">
      <MessageList :messages="messages" />
    </div>
    <div class="chat-input">
      <textarea 
        v-model="messageContent" 
        placeholder="输入您的消息..."
        @keyup.enter="sendMessage"
      ></textarea>
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import MessageList from './MessageList.vue';
import { chatService } from '@/services/chat.service';
import { useAuthStore } from '@/stores/auth.store';

const props = defineProps({
  courseId: {
    type: Number,
    required: true
  },
  courseName: {
    type: String,
    default: '课程聊天室'
  }
});

const authStore = useAuthStore();
const messages = ref([]);
const messageContent = ref('');
const messageContainer = ref(null);

const sendMessage = async () => {
  if (!messageContent.value.trim()) return;

  try {
    await chatService.sendMessage(props.courseId, messageContent.value);
    messageContent.value = '';
    await fetchMessages();
  } catch (error) {
    console.error('发送消息失败', error);
  }
};

const fetchMessages = async () => {
  try {
    messages.value = await chatService.getCourseMessages(props.courseId);
    await nextTick(() => {
      if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
      }
    });
  } catch (error) {
    console.error('获取消息失败', error);
  }
};

onMounted(() => {
  fetchMessages();
});
</script>

<style scoped lang="scss">
.chat-window {
  display: flex;
  flex-direction: column;
  height: 500px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;

  .chat-header {
    background-color: #f5f5f5;
    padding: 10px;
    border-bottom: 1px solid #e0e0e0;
  }

  .chat-messages {
    flex-grow: 1;
    overflow-y: auto;
    padding: 10px;
  }

  .chat-input {
    display: flex;
    padding: 10px;
    background-color: #f5f5f5;
    border-top: 1px solid #e0e0e0;

    textarea {
      flex-grow: 1;
      margin-right: 10px;
      resize: none;
      height: 80px;
    }

    button {
      padding: 10px 20px;
      background-color: #3498db;
      color: white;
      border: none;
      border-radius: 4px;
    }
  }
}
</style>